package cn.xxd.xxdssoservice.service;

import cn.xxd.common.StringUtils;
import cn.xxd.entity.LoginUser;
import cn.xxd.entity.ReturnT;
import cn.xxd.entity.ShopUser;
import cn.xxd.xxdssointerface.RegisterService;
import cn.xxd.xxdssoservice.dao.LoginUserDao;
import cn.xxd.xxdssoservice.dao.ShopUserDao;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service(version = "1.0.0", interfaceClass = RegisterService.class)
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private LoginUserDao loginUserDao;

    @Autowired
    private ShopUserDao shopUserDao;

    @Override
    public ReturnT checkData(String param, int type) {
        //数据有效性校验
        if (param == null || "".equals(param)) {
            return new ReturnT(400, "请输入邮箱！");
        }
        //验证邮箱格式
        String regex = "\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
        if (!param.matches(regex)) {
            return new ReturnT(400, "请输入正确邮箱格式！");
        }

        return new ReturnT(200, "success");
    }

    @Override
    public ReturnT register(LoginUser user) {

        //数据有效性校验
        if (StringUtils.isBlank(user.getPassword())) {
            return new ReturnT(400, "请输入密码！");
        }

        String reg_pwd = "^[A-Za-z0-9]{8,12}$";
        if (!user.getPassword().matches(reg_pwd)) {
            return new ReturnT(400, "密码必须由字母+数字组合，长度9-12位");
        }

        //邮箱是否被注册
        ShopUser result_shopUser = shopUserDao.chechEmaill(user.getUsername());
        if (result_shopUser != null) {
            return new ReturnT(400, "该邮箱已被注册！");
        }

        //用户信息录入
        ShopUser shopUser = new ShopUser();
        shopUser.setEmaill(user.getUsername());
        shopUser.setDel("0");
        shopUserDao.insertSelective(shopUser);

        //用户登录信息录入
        user.setCreated(new Date());
        user.setUpdated(new Date());
        //对密码进行md5加密
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        user.setUser_id(shopUser.getId());
        user.setDel("0");
        //设置盐
        String saltStr = UUID.randomUUID().toString();
        user.setSalt(saltStr);
        //把用户数据插入到数据库中
        loginUserDao.insertSelective(user);
        //返回添加成功
        return new ReturnT(200, "注册成功！");
    }


}
